<template>
  <div>
    <el-dialog v-model="dialog.visible" :title="dialog.title" @close="hide()">
      <div class="relative flex items-center stroeList">
        <div class="shrink-0 lable"><span class="red">*</span> 商品库</div>
        <div class="flex w-full justify-start ml-[10px] items-center inputVal" style="justify-content: start !important" @click="handleCateList">
          {{ productStoreName }}1
        </div>
        <div class="w-full absolute left-[46px] top-[35px] lisbox" v-if="showCateList">
          <div class="w-[50%] ml-[15px] val">
            <!-- <el-select v-model="productStoreId" placeholder="请选择商品库">
            <el-option v-for="(item, index) in productStoreList" :key="index" :label="item.productStoreCatetoryName" :value="index" />
          </el-select> -->
            <div class="h-[200px] w-[400px] flex absolute z-10 bg-[#fff] overflow-hidden cate">
              <div class="w-[50%] shrink-0 h-[200px] overflow-y-scroll left">
                <div
                  class="flex justify-between items-center px-[10px] py-[6px] subitems cursor-pointer hover:bg-[#ccc]"
                  v-for="(item, index) in productStoreCateList"
                  :key="index"
                  :class="subCategoryIndex === index ? 'bg-[#ccc] active' : ''"
                  @click="handelCategory(index)"
                >
                  <div class="txt">{{ item.productStoreCatetoryName }}</div>
                  <div class="arrows">
                    <el-icon size="10"><ArrowRight /></el-icon>
                  </div>
                </div>
              </div>
              <div class="w-[50%] shrink-0 h-[200px] overflow-y-scroll right">
                <div
                  class="flex justify-between items-center px-[10px] py-[6px] subitems cursor-pointer hover:bg-[#ccc]"
                  v-for="(item, index) in productStoreCateList[subCategoryIndex]?.productStoreList"
                  :key="index"
                  :class="productStoreId === item.platformId ? 'bg-[#ccc] active' : ''"
                  @click="handelProductStoreId(index)"
                >
                  <div class="txt">{{ item.name }}</div>
                  <div class="arrows"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="flex items-start mt-[20px] left">
          <div class="userlist"></div>
          <div class="flex flex-col productlist">
            <div class="flex items-center searchbox">
              <el-input v-model="keywords" placeholder="请输入关键词" />
              <el-button class="ml-[15px]" @click="getProjectListRes">查询</el-button>
            </div>
            <div class="pt-[15px] flex">
              <div class="w-[898px] border-solid border-1px border-[#dcdfe6] pb-[30px] contlist">
                <div class="cont">
                  <el-table
                    class="myTable"
                    height="440"
                    ref="tableRef"
                    :data="productList"
                    row-key="productId"
                    @selection-change="handleSelectionChange"
                    @row-click="handelRowClick"
                    v-loading="loading"
                  >
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="name" label="名称" />
                    <el-table-column property="productId" label="ID" />
                  </el-table>
                  <pagination
                    size="small"
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getProjectListRes"
                  />
                </div>
              </div>
              <div class="text-[14px] ml-[10px] h-[440px] w-[200px] selectlist" style="display: none">
                <div class="flex justify-between items-center border-solid border-1px px-[15px] py-[4px] border-[#dcdfe6] selectAcout">
                  <div class="numtxt">已选({{ selectRows.length }})</div>
                  <div class="cursor-pointer action" :class="selectRows.length ? 'text-[#297bfb]' : 'text-[#a9c5f1]'" @click="clearAll">清空</div>
                </div>
                <div class="h-[411px] border-solid border-1px border-[#dcdfe6] border-t-0 listbox"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button plain @click="hide()">取消</el-button>
        <el-button type="primary" plain @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getProductStoreList, getProductList, getProductStoreCatetoryList } from '@/api/dramaComponent';
import { ProductStoreVO, ProductItemVO, ProductListQuery, ProductStoreCateVO } from '@/api/dramaComponent/types';
import { useAppStore } from '@/store/modules/app';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const appStore = useAppStore();

const emit = defineEmits(['getProduct']);
type SelectAccountType = {
  id: number | string;
  name: string;
  appId?: string;
  appName?: string;
  limit?: number;
  isCur?: boolean;
  instanceId?: string;
  assetId?: number;
};

const props = defineProps<{
  advertiserId: SelectAccountType[];
  productId: number;
}>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '商品选择'
});

const showCateList = ref(false);

const subCategoryIndex = ref(0);

const keywords = ref('');

const loading = ref(false);

const productList = ref<ProductItemVO[]>([]);

const selectRows = ref<ProductItemVO[]>([]); //考虑后期多帐号对应不同商品

const tableRef = ref(null);

const total = ref(0);

const productStoreId = ref<number>();
const productStoreName = ref(null);
const productStoreCateList = ref<ProductStoreCateVO[]>([]);

const initFormQuery: ProductListQuery = {
  pageNum: 1,
  pageSize: 100,
  accountId: appStore.accountId, //账号id
  advertiserId: null, //广告主ID
  productPlatformId: null, //商品库id
  productId: null, //商品id
  productName: null, //商品名称
  dpaCategories: null //商品行业分类，长度限制 50，使用的三级行业ID
};

const queryParams = ref<ProductListQuery>({ ...initFormQuery });

const handelRowClick = (row) => {
  const checkRowIndex = selectRows.value.findIndex((item) => item.productId === row.productId);

  if (checkRowIndex !== -1) {
    tableRef.value?.toggleRowSelection(row, false);
    selectRows.value.splice(checkRowIndex, 1);
    clearAll();
  } else {
    if (selectRows.value.length) {
      selectRows.value.splice(0, 1);
    }
    tableRef.value?.toggleRowSelection(row, true);
    selectRows.value.push(row);
  }
};

const handleSelectionChange = (selection: ProductItemVO[]) => {
  if (selection.length) {
    selection.map((item, index) => {
      if (index === selection.length - 1) {
        tableRef.value?.toggleRowSelection(item, true);
        selectRows.value.push(item);
      } else {
        selection.splice(index, 1);
        selectRows.value.splice(index, 1);
        tableRef.value?.toggleRowSelection(item, false);
      }
    });
  } else {
    selectRows.value = [];
    tableRef.value?.clearSelection();
  }
};
const clearAll = () => {
  selectRows.value = [];
  tableRef.value?.clearSelection();
};
const handelCategory = (i: number) => {
  subCategoryIndex.value = i;
};

const handelProductStoreId = (i: number) => {
  showCateList.value = false;
  productStoreId.value = productStoreCateList.value[subCategoryIndex.value]['productStoreList'][i]['platformId'];
  productStoreName.value = productStoreCateList.value[subCategoryIndex.value]['productStoreList'][i]['name'];
};

const handleCateList = () => {
  showCateList.value = !showCateList.value;
};

const submit = () => {
  if (selectRows.value.length === 0) {
    proxy?.$modal.msgError('请选择商品');
    return;
  }
  emit('getProduct', { productPlatformId: productStoreId.value, productId: selectRows.value[0].productId, productName: selectRows.value[0].name });
  hide();
};

// watch(
//   () => selectRows.value,
//   () => {
//     console.log(selectRows.value);
//   }
// );

/**
 * 请求商品库下面商品列表
 * */
const getProjectListRes = async () => {
  loading.value = true;
  queryParams.value.advertiserId = props.advertiserId ? (props.advertiserId[0].id as number) : null;
  queryParams.value.productPlatformId = productStoreId.value;
  queryParams.value.productName = keywords.value;
  const res = await getProductList(queryParams.value);
  total.value = res.total || 1;
  productList.value = res.data;

  if (props.productId) {
    productList.value.map((item) => {
      if (item.productId === props.productId) {
        setTimeout(() => {
          tableRef.value?.toggleRowSelection(item, true);
        }, 20);
      }
    });
  }

  loading.value = false;
};

watch(
  () => props.advertiserId,
  (newVal) => {
    if (newVal) {
      init();
    }
  }
);
watch(
  () => productStoreId.value,
  (newVal) => {
    if (newVal) {
      getProjectListRes();
    }
  }
);

const init = async () => {
  if (props.advertiserId.length) {
    const res = await getProductStoreCatetoryList({ accountId: appStore.accountId, advertiserId: props.advertiserId[0].id as number });
    productStoreCateList.value = res.data;
  }
};

onMounted(() => {
  nextTick(() => {
    init();
  });
});

const show = () => {
  if (!props.advertiserId) return;
  dialog.visible = true;
};
const hide = () => {
  showCateList.value = false;
  dialog.visible = false;
};

defineExpose({ show, hide });
</script>

<style lang="scss" scoped>
::v-deep(.myTable) {
  thead {
    th:nth-child(1) {
      .cell {
        display: none;
      }
    }
  }
}
.lisbox {
  .cate {
    box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
  }
}
</style>
